import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';

/*
  Generated class for the HttpserviceProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class HttpserviceProvider {

    constructor(public http: HttpClient) {
        console.log('Hello HttpserviceProvider Provider');
    }

    /**
     * 获取服务器地址
     */
    private getServerUrl() {
        let url = localStorage.getItem("address")+"/ecard";
        return url;
    }

    /**
     * 设置请求头 content-type json
     */
    private getJsonRequestOptions() {

        let headers: HttpHeaders = new HttpHeaders({
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*'
        });
        let options = {headers: headers};
        return options;
    }

    /**
     * 发送post请求
     */
    public post(url,param?): Observable<any> {
        let body = "";
        if(param!=null){
            body = JSON.stringify(param);
        }
        let userid = localStorage.getItem("userid");
        let serverUrl = this.getServerUrl();
        let finalUrl = serverUrl + url;
        if(finalUrl.indexOf("?")>=0){
            finalUrl = finalUrl +"&userid="+userid;
        }else{
            finalUrl = finalUrl+"?userid="+userid;
        }
        return this.http.post(finalUrl, body, this.getJsonRequestOptions());
    }
}
